﻿
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Concurrent;
using System.Configuration;
using Best.SmartCms.Core.Utility;
using Best.SmartCms.Domain;
using Best.SmartCms.Utility;

namespace Best.SmartCms.Dao.Common
{
    public class DbContextBuilder
    {
        private const string BasicDataConnStringPrefix = "MySqlConnectionString";

        private static readonly ConcurrentDictionary<string, DbContextOptions<MySqlDbContext>> BasicDbOptionMap =
            new ConcurrentDictionary<string, DbContextOptions<MySqlDbContext>>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connStringNameSuffix"></param>
        /// <returns></returns>
        public static MySqlDbContext GetBasicDbContext(string connStringNameSuffix = "")
        {
            try
            {
                if (BasicDbOptionMap.TryGetValue(connStringNameSuffix, out var options))
                {
                    return new MySqlDbContext(options);
                }
                var connectionStringKey = GenerateConnStringName(BasicDataConnStringPrefix, connStringNameSuffix);
                options = GetBasicDbContextOptions(connectionStringKey);
                BasicDbOptionMap.TryAdd(connStringNameSuffix, options);
                return new MySqlDbContext(options);
            }
            catch (Exception ex)
            {
                NLogManager.LogError("DbContextBuilder GetBasicDbContext", ex);
                throw;
            }
        }

        private static string GenerateConnStringName(string prefix, string connString)
        {
            return string.IsNullOrEmpty(connString) ? prefix : string.Format("{0}_{1}", prefix, connString);
        }

        private static DbContextOptions<MySqlDbContext> GetBasicDbContextOptions(string connString)
        {
            var connectionStringValue = ConfigurationManager.AppSettings[$"ConnectionStrings:{connString}"];
            if (string.IsNullOrEmpty(connectionStringValue))
                throw new Exception(
                    $"DbContextBuilder GetDbContextOptions ConnectionString:{connString} not found.");

            var builder = new DbContextOptionsBuilder<MySqlDbContext>().UseMySql(connectionStringValue);
            return builder.Options;
        }
    }
}
